package com.nmgydy.admin.controller;

import com.alibaba.fastjson.JSON;
import com.nmgydy.beans.ListBean;
import com.nmgydy.beans.Message;
import com.nmgydy.model.Module;
import com.nmgydy.model.ModuleRole;
import com.nmgydy.model.Role;
import com.nmgydy.util.Functions;
import com.nmgydy.util.HibernateDao;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/role")
public class RoleController {
	@Autowired
	private HibernateDao hibernateDao;

	@RequestMapping("list")
	public String list(){
		return "/admin/role/list";
	}
	@RequestMapping("add")
	public String add(){
		return "/admin/role/add";
	}
	@RequestMapping("edit")
	public String edit(){
		return "/admin/role/edit";
	}

	@RequestMapping("moduleRole")
	public String moduleRole(String roleId,Model model){
		model.addAttribute("roleId", roleId);
		return "/admin/role/moduleRole";
	}
	@ResponseBody
	@RequestMapping("listData")
	public String listData(Role vo, HttpServletRequest request) throws Exception{
		String pageSize = request.getParameter("pageSize");
		String pageIndex = request.getParameter("pageIndex");
		String sortField = request.getParameter("sortField");
		String sortOrder = request.getParameter("sortOrder");
		String name = request.getParameter("name");
		String hql = "from Role where id=id";
		Map<String,Object> params = new HashMap<String,Object>();
		if (!Functions.isEmpty(name)) {
			hql += " and name like :name";
			params.put("name", "%"+name+"%");
		}
		if(!Functions.isEmpty(sortField)&&!Functions.isEmpty(sortOrder)){
			hql += " order by " + sortField + " " + sortOrder;
		}
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>) hibernateDao.list(hql, params, Integer.parseInt(pageIndex)+1, Integer.parseInt(pageSize));
		int total = (int) hibernateDao.count(hql, params);
		return JSON.toJSONString(new ListBean(roleList,total));
	}

	@ResponseBody
	@RequestMapping("save")
	public String save(Role record) throws Exception{
		boolean flag = hibernateDao.save(record);
		Message message=new Message();
		if(flag){
			message.setRes(true);
			message.setMsg("添加成功");
		}else{
			message.setRes(false);
			message.setMsg("添加失败");
		}
		return JSON.toJSONString(message);
	}

	@ResponseBody
	@RequestMapping("update")
	public String update(Role record) throws Exception{
		if(record.getId()==null){
			Logger.getLogger(RoleController.class).error("roleId is null");
			return JSON.toJSONString(new Message(false,"修改失败"));
		}
		boolean flag = hibernateDao.update(record);
		Message message=new Message();
		if(flag){
			message.setRes(true);
			message.setMsg("修改成功");
		}else{
			message.setRes(false);
			message.setMsg("修改失败");
		}
		return JSON.toJSONString(message);
	}

	@ResponseBody
	@RequestMapping("remove")
	public String delete(Integer id) throws Exception{
		if(id == null){
			Logger.getLogger(RoleController.class).error("ID is null");
			return JSON.toJSONString(new Message(false,"删除失败"));
		}
		Message message = new Message();
		Role role = hibernateDao.load(Role.class, id);
		boolean flag = hibernateDao.delete(role);
		if (flag) {
			message.setRes(true);
			message.setMsg("删除成功");
		} else {
			message.setRes(false);
			message.setMsg("删除失败");
		}

		return JSON.toJSONString(message);
	}

	@ResponseBody
	@RequestMapping("moduleRoleData")
	public String moduleRoleData(Integer roleId, HttpServletRequest request) throws Exception{
		if(roleId == null){
			return JSON.toJSONString(new Message(false,"roleId is null."));
		}
		//获取全部的模块信息
		List<Module> moduleList = (List<Module>) hibernateDao.list("from Module");
		//获取角色的模块功能点信息
		String hql = "from ModuleRole where roleId=:roleId";
		Map<String,Object> params = new HashMap<>();
		params.put("roleId", roleId);
		List<ModuleRole> moduleRoleList = (List<ModuleRole>) hibernateDao.list(hql,params);

		for(Module module : moduleList){
			boolean checked = false;
			for(ModuleRole moduleRole : moduleRoleList){
				if(moduleRole.getModuleId().equals(module.getId())){
					checked = true;
					break;
				}
			}
			module.setChecked(checked);
		}

		return JSON.toJSONString(moduleList);
	}

	@ResponseBody
	@RequestMapping("updateModuleRole")
	public String updateModuleRole(Integer roleId,String data) throws Exception{
		if(roleId == null){
			return JSON.toJSONString(new Message(false,"roleId is null"));
		}
		if(Functions.isEmpty(data)){
			return JSON.toJSONString(new Message(false,"data is null"));
		}
		String[] dataArr = data.split(",");
		if(dataArr.length <= 0){
			return JSON.toJSONString(new Message(false,"data size 0"));
		}
		List<Integer> moduleIdList = new ArrayList<>();
		for(String item : dataArr){
			moduleIdList.add(Integer.parseInt(item));
		}
		Session session = null;
		Transaction transaction;
		try{
			session = hibernateDao.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			session.createQuery("delete from ModuleRole where roleId=:roleId")
					.setParameter("roleId", roleId).executeUpdate();
			for (Integer moduleId : moduleIdList) {
				ModuleRole moduleRole = new ModuleRole();
				moduleRole.setRoleId(roleId);
				moduleRole.setModuleId(moduleId);
				session.save(moduleRole);
			}
			transaction.commit();
			return JSON.toJSONString(new Message(true,"更新成功"));
		}catch(Exception e){
			e.printStackTrace();
			return JSON.toJSONString(new Message(false,"更新失败"));
		}finally{
			if(session != null){
				session.close();
			}
		}
	}

}
